#!/usr/bin/python

import MySQLdb
import os
import string
import sys
import re
import time
import zipfile
from datetime import datetime
import numpy
import matplotlib
from pylab import *


# check if the number of arguments is correct
if(len(sys.argv) != 5):
    print "Error:\tLess than 6 arguments provided"
    print "Usage:\tdatabase_loader.py host user password database"
    print "Example:\tdatabase_loader.py localhost slamusers slamusers slamusers"
    sys.exit(0)


# params to the script for loading
host = sys.argv[1]
user = sys.argv[2]
password = sys.argv[3]
database = sys.argv[4]

# dump the info just in case
print ""
print "Database Host: %s" % host
print "Database: %s" % database
print ""
print "Waiting 1 seconds before continuing..."
time.sleep(1);



# setup the database connection we're using
conn = MySQLdb.connect (host, user, password, database)
cursor = conn.cursor ()

# the lines we're interested in comparing
lines = ('hulk','shrek', 'otg')
line2 = ('immatureT')
# minimum number of probes to look at
probes = 1

chromosomes=('chr1', 'chr2', 'chr3', 'chr4', 'chr5', 'chr6','chr7', 'chr8', 'chr9', 'chr10', 'chr11', 'chr12', 'chr13', 'chr14', 'chr15', 'chr16','chr17', 'chr18', 'chr19', 'chr20', 'chr21', 'chr22', 'chr23', 'chr24', 'chr25', 'chrM')


# create a new figure
fig = matplotlib.pyplot.figure()

# for all the chromosomes
for chr in chromosomes:
    i = chromosomes.index(chr)
    
    print "Plotting: " + chr

    first = fig.add_subplot(len(chromosomes),1,i)
    
    
    # lets put all the lines on a single chromosome to compare
    for line1 in lines:
        
        
        sql = "select start_position, (average_treat_p - avg_con_p) from bed_data where chromosome = '"+ chr + "' and line1 = '" + line1 + "' and line2 = '" + line2 + "' and n_probes >= " + str(probes) + " order by start_position"
    
        # perform the query
        try:
            cursor.execute(sql)        
        except Exception, e:
            print e
            print "Error executing SQL Statement: " + sql
            
            
        # fetch the results and create scores list
        results = cursor.fetchall()
        diff = []
        position = []
        for x in results:
            position.append(x[0])
            diff.append(x[1])
            
        
        # fetch the results and create scores list
        first.plot(diff)
        #first.set_xlabel('Start Position')
        #first.set_ylabel('Change in Methylation Relative to immatureT')
        first.set_ylim( -1, 1)
        #first.set_xticks(position)

        #first.set_title(sql, fontsize='xx-small')
        first.grid(True)
        #first.legend(loc='upper center')
fig.show()
#fig.savefig(chr + '-ProbeCutoff-' + str(probes) + '.pdf')
    
    
    
        
        
        
        
        
        
        
        
        
        
        
        
        
